<template>
  <div class="container">
    <div class="app-container">

      <!-- 表格  -->
      <el-button type="primary" size="mini" @click="add">添加角色</el-button>
      <!-- <el-button type="text" @click="dialogVisible = true">点击打开 Dialog</el-button> -->

      <el-dialog
        title="提示"
        :visible.sync="dialogVisible"
        width="40%"
        :before-close="handleClose"
      >
        <el-form ref="foemRole" :model="foemRole" :rules="rules">
          <el-form-item prop="name" label="角色名称">
            <el-input v-model="foemRole.name" style="width:300px" size="mini" />
          </el-form-item>
          <el-form-item prop="state" label="启用">
            <el-switch
              v-model="foemRole.state"
              :inactive-value="0"
              :active-value="1"
              active-color="#13ce66"
              inactive-color="#ff4949"
            />
          </el-form-item>
          <el-form-item prop="description" label="角色描述">
            <el-input
              v-model="foemRole.description"
              type="textarea"
              :rows="2"
              placeholder="请输入内容"
            />
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="cance">取 消</el-button>
          <el-button type="primary" @click="sure">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 表格 -->
      <el-table :data="roleList">
        <el-table-column align="center" prop="name" width="200" label="角色">
          <template v-slot="{row}">
            <el-input v-if="row.isEdit" v-model="row.rowEdit.name" size="mini" />
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="state" width="200" label="启用">
          <template #default="{row}">
            <el-row v-if="row.isEdit">
              <el-switch v-model="row.rowEdit.state" size="mini" :active-value="1" :inactive-value="0" />
            </el-row>
            <span v-else>{{ row.state === 1 ? "已启用":row.state=== 0? "未启用":"无" }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="description" label="描述">
          <template #default="{row}">
            <el-input v-if="row.isEdit" v-model="row.rowEdit.description" size="mini" type="textarea" />
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="" label="操作">
          <template #default="{row}">
            <template v-if="row.isEdit">
              <el-button size="mini" type="primary" @click="confirnEdit(row)">确定</el-button>
              <el-button size="mini" @click="row.isEdit= false">取消</el-button>
            </template>
            <template v-else>
              <el-button type="text" size="mini" @click="btnPermission(row.id)">分配权限</el-button>
              <el-button type="text" size="mini" @click="edit(row)">编辑</el-button>
              <el-popconfirm
                title="这是一段内容确定删除吗？"
                @onConfirm="onConfirm(row.id)"
              >
                <!-- <el-button type="text" size="mini">删除</el-button> -->
                <el-button slot="reference" type="text" style="margin:5px" size="mini">删除</el-button>
              </el-popconfirm>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-row type="flex" style="height:60px" align="middle" justify="end">
        <el-pagination
          :current-page="pageParams.page"
          :page-size="pageParams.pagesize"
          :total="pageParams.total"
          layout="prev, pager, next"
          @current-change="handleCurrentChange"
        />

      </el-row>
      <!-- 表单 -->

    </div>
    <el-dialog
      title="分配权限"
      :visible.sync="shoPermissionDialog"
    >
      <el-tree
        ref="permTree"
        check-strictly
        node-key="id"
        :default-checked-keys="permId"
        default-expand-all
        show-checkbox
        :data="permissioData"
        :props="{label:'name'}"
      />
      <template>
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button size="mini">取 消</el-button>
            <el-button size="mini" type="primary" @click="btnPermissionOk">确 定</el-button>
          </el-col>
        </el-row>
      </template>
    </el-dialog>

  </div>
</template>
<script>
import { addRole, delRole, getRoleDetail, getRoleList, updateRole, assignPrem } from '@/api/role'
import { getPermissionList } from '@/api/permission'
import { translateListToTree } from '@/utils'
export default {
  name: 'Role',
  data() {
    return {
      currentRoledId: [],
      shoPermissionDialog: false,
      permissioData: [],
      roleList: [],
      permId: [],
      pageParams: {
        page: 1,
        pagesize: 5,
        total: 0 // 总条数
      },
      dialogVisible: false,
      foemRole: {
        name: '',
        state: 0,
        description: ''
      },
      rules: {
        name: [{ required: true, message: '不能为空', trigger: 'blur' }],
        description: [{ required: true, message: '不能为空', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getRoleList()
  },

  methods: {
    // dian
    async btnPermissionOk() {
      await assignPrem({ id: this.currentRoledId, permIds: this.$refs.permTree.getCheckedKeys() })
      this.$message.success('分配权限成功')
      this.shoPermissionDialog = false
    },
    // 点击弹出层
    async btnPermission(id) {
      // 分配权限bug处理,清空id
      this.permId = []
      // 转化数据
      this.permissioData = translateListToTree(await getPermissionList(), 0)
      //
      this.currentRoledId = id// 记录id
      const { permIds } = await getRoleDetail(id)// 获取详情
      this.permId = permIds// 赋值数据
      // console.log(res)
      this.shoPermissionDialog = true// 打开弹层
    },
    // 点击弹框
    add() {
      this.dialogVisible = true
    },
    // 取消
    cance() {
      this.dialogVisible = false
      // this.$refs.form.resetFields()
      this.handleClose()
    },
    //
    async sure() {
      // await this.$refs.form.validate()
      await this.$refs.foemRole.validate()
      // console.log(111)
      const res = await addRole(this.foemRole)
      console.log(res)
      this.getRoleList()
      this.handleClose()
    },
    handleClose() {
      this.$refs.foemRole.resetFields()
      this.dialogVisible = false
    },
    handleCurrentChange(val) {
      this.pageParams.page = val
      this.getRoleList()
    },
    // 获取-分页查询角色列表
    async getRoleList() {
      const { rows, total } = await getRoleList(this.pageParams)
      // console.log(res)
      this.roleList = rows
      this.pageParams.total = total
      this.roleList.forEach(item => {
        // item.isEdit = false
        // object.defineProperty
        // vue中动态添加的属性，不具备响应式的能力
        // 响应式：数据变化，视图更新
        // 如何动态往对象中添加属性，还具备响应式能力
        // this.$set(目标对象，'属性'，属性值)
        // item.isEdit = false // isEdit 是否进入编辑状态 默认是false
        this.$set(item, 'isEdit', false)
        this.$set(item, 'rowEdit', {
          name: item.name,
          state: item.state,
          description: item.description
        })
      })
    },
    // 编辑行
    edit(row) {
      console.log(row)
      row.isEdit = true // 进入编辑状态
      // 更新缓存数据
      row.rowEdit = {
        name: row.name,
        state: row.state,
        description: row.description
      }
    },
    // 点击确定
    async confirnEdit(row) {
      // 判断表单的值是否为空
      if (row.rowEdit.name && row.rowEdit.description) {
        // 发送请求 更新数据
        await updateRole({ ...row.rowEdit, id: row.id })
        // 更新显示数据
        // eslint-disable-next-line require-atomic-updates
        // row.name = row.rowEdit.name //eslint 校验工具 误判
        // // eslint-disable-next-line require-atomic-updates
        // row.state = row.rowEdit.state //eslint 校验工具 误判
        // eslint-disable-next-line require-atomic-updates
        // row.description = row.rowEdit.description //eslint 校验工具 误判
        this.$message.success('更新角色成功')
        Object.assign(row, {
          isEdit: false,
          ...row.rowEdit
        })
        // 推出编辑状态
      } else {
        this.$message.warning('名称和描述不能为空')
      }
    },
    // 删除
    async onConfirm(id) {
      console.log(id)
      await delRole(id)
      this.getRoleList()
    }
  }
}
</script>
<style scoped>
.app-container{
  margin: 10px;
}
</style>
